<template>
  <el-card>
    <!-- 标题 -->
    <template #header>
      <h2>班级管理
        <el-button type="primary" @click="addDrawer=true">添加班级</el-button>
      </h2>
    </template>
    <!-- 班级管理信息展示 -->

      <div style="margin-top: 15px;">
        <el-input placeholder="请输入搜索内容" v-model="searchValue">
          <el-select style="width: 100px" v-model="searchField" slot="prepend" placeholder="请选择">
            <el-option label="班级名" value="classname"></el-option>
          </el-select>
          <el-button @click="getClasses(params)" slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </div>
      <el-table v-loading="loading" :data="classes" border stripe>
        <el-table-column align="center" prop="classname" label="班级" width="200px"></el-table-column>
        <el-table-column align="center" prop="ctime" label="日期" width="200px">
          <template #default="{row}">{{moment(row.ctime).locale('zh-cn').fromNow()}}</template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="376px">
          <template #default="{row}">
            <el-button type="primary" plain @click="editShow(row)">
              编辑<i class="el-icon-edit"></i></el-button>
            <el-button type="danger" plain @click="del(row._id)">
              删除<i class="el-icon-delete"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-drawer v-loading="addLoading"
      size="400px" title="添加班级" :visible.sync="addDrawer" direction="rtl">
        <el-form style="padding:10px" :model="addForm" :rules="addRules" ref="addForm">
          <el-form-item label="班级名称" prop="classname">
            <el-input v-model="addForm.classname"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addSave">保存</el-button>
            <el-button @click="addDrawer=false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>

      <el-drawer v-loading="editLoading"
      size="400px" title="编辑班级" :visible.sync="editDrawer" direction="rtl">
        <el-form style="padding:10px" :model="editForm" :rules="editRules" ref="editForm">
          <el-form-item label="班级名称" prop="classname">
            <el-input v-model="editForm.classname"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="editSave">保存</el-button>
            <el-button @click="editDrawer=false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>

      <el-pagination @current-change="change" style="margin:10px 0" :page-size="perPage"
      background layout="prev, pager, next" :total="count"></el-pagination>

  </el-card>
</template>

<script>
import { createNamespacedHelpers } from 'vuex';
import moment from 'moment';

const { mapActions, mapState } = createNamespacedHelpers('classes');

export default {
  data() {
    // 验 证
    const validateClassname = async (rule, value, callback) => {
      const { data } = await this.apis.classesExist({
        field: 'classname',
        value,
      });
      if (!data) {
        callback();
      } else {
        callback(new Error('用户名已存在'));
      }
    };
    const editValidateClassname = (rule, value, callback) => {
      if (value === this.row.classname) {
        callback();
      } else {
        validateClassname(rule, value, callback);
      }
    };
    return {
      row: {},
      page: 1,
      perPage: 2,
      searchField: '',
      searchValue: '',
      addDrawer: false,
      addLoading: false,
      addForm: {},
      // 添加班级验证规则
      addRules: {
        classname: [
          { required: true, message: '请输入班级名', trigger: 'blur' },
          { validator: validateClassname, trigger: 'blur' },
        ],
      },
      editLoading: false,
      editDrawer: false,
      editForm: {
        classname: '',
      },
      // 编辑班级验证规则
      editRules: {
        classname: [
          { required: true, message: '请输入班级名', trigger: 'blur' },
          { validator: editValidateClassname, trigger: 'blur' },
        ],
      },
    };
  },
  computed: {
    params() {
      const p = {
        perPage: this.perPage,
        page: this.page,
      };
      if (this.searchField && this.searchValue) {
        p.searchField = this.searchField;
        p.searchValue = this.searchValue;
      }
      return p;
    },
    ...mapState(['classes', 'count', 'loading']),
  },
  created() {
    this.getClasses(this.params);
  },
  methods: {
    // 删除班级
    del(id) {
      this.$confirm('确定删除吗？').then(async () => {
        await this.apis.deleteClasses(id);
        this.getClasses(this.params);
      }).catch(() => {});
    },
    // 保存编辑班级
    editSave() {
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) {
          return;
        }
        this.editLoading = true;
        const { _id: id } = this.row;
        const data = {};
        if (this.editForm.classname !== this.row.classname) {
          data.classname = this.editForm.classname;
        }
        await this.apis.editClasses(id, data);
        this.getClasses(this.params);
        this.editLoading = false;
        this.editDrawer = false;
      });
    },
    // 编辑班级数据展示
    editShow(row) {
      this.row = row;
      this.editForm.classname = row.classname;
      this.editDrawer = true;
    },
    // 保存添加班级
    addSave() {
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) {
          return;
        }
        this.addLoading = true;
        await this.apis.addClasses({
          classname: this.addForm.classname,
        }).catch(() => {
          this.addLoading = false;
        });
        this.getClasses(this.params);
        this.addLoading = false;
        this.addDrawer = false;
      });
    },
    change(e) {
      this.page = e;
      this.getClasses(this.params);
    },
    moment,
    ...mapActions(['getClasses']),
  },
};
</script>
